package org.example.mybatis.plus.boot3.service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.example.mybatis.plus.boot3.entity.User;
import org.example.mybatis.plus.boot3.mapper.UserMapper;
import org.example.mybatis.plus.boot3.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceUseMapper {
    @Autowired
    private UserMapper userMapper;

    public int save(User user) {
        if (user.getId() == null) {
            return userMapper.insert(user);
        } else {
            return userMapper.updateById( user);
        }
    }

    public int deleteById(Long id) {
        return userMapper.deleteById(id);
    }

    public User findById(Long id) {
        return userMapper.selectById( id);
    }

    public List<User> findAll() {
        return userMapper.selectList(null);
    }

    public IPage<UserVo> getUserVoPage(int current, int size) {
        Page<UserVo> page = new Page<>(current, size);
        return userMapper.selectPageVo(page);
    }

    /**
     * 更新用户信息（带乐观锁）
     * 如果版本号不匹配，会抛出异常
     */
    public boolean updateUser(User user) {
        // MyBatis-Plus 会自动处理版本号的比较和更新
        int result = userMapper.updateById(user);
        return result > 0;
    }

}
